package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.redis.KeyPrefix;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.util.MD5Util;
import cn.wolfcode.shop.cloud.util.MemberCodeMsg;
import cn.wolfcode.shop.cloud.util.MemberkeyPrefix;
import cn.wolfcode.shop.cloud.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public User selectOne(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public String doLogin(LoginVo loginVo) {
        //1、判断是否为空
        //if(!StringUtils.hasLength(loginVo.getUsername())||!StringUtils.hasLength(loginVo.getPassword())){
        //    throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        //}
        //2、根据账号去数据库查询是否有数据
        User user = this.selectOne(Long.valueOf(loginVo.getUsername()));
        if(user==null){
            throw new BusinessException(MemberCodeMsg.LOGIN_OPT);
        }
        //3、对比密码
        String pass = MD5Util.encode(loginVo.getPassword(), user.getSalt());
        if(!(pass.equals(user.getPassword()))){
            throw new BusinessException(MemberCodeMsg.LOGIN_OPT);
        }
        String token = createToken(user);
        return token;
    }

    @Override
    public void refreshRedis(String token) {
        //先判断token是否存在
        if(redisService.exists(MemberkeyPrefix.USER_TOKEN, token)){
            //若存在，延长redis的存活时间
            redisService.expire(MemberkeyPrefix.USER_TOKEN, token,1800);
        }
    }

    //从redis中去获取当前登录用户信息
    @Override
    public User queryUser(String token) {
        //先判断token是否为空
        if(!StringUtils.isEmpty(token)){
            //当token不为空时，从redis中去获取当前登录用户对象的信息
            User user = redisService.get(MemberkeyPrefix.USER_TOKEN, token, User.class);
            return user;
        }
        return null;
    }

    private String createToken(User user){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //将token储存到redis中去
        redisService.set(MemberkeyPrefix.USER_TOKEN, token,user);
        return token;
    }
}
